package com.wqnmdb.im.netty.handler.impl;

import com.wqnmdb.im.domain.contants.ConstantEnum;
import com.wqnmdb.im.domain.netty.protobuf.NettyModel;
import com.wqnmdb.im.netty.dispose.MsgDispose;
import com.wqnmdb.im.netty.dispose.NettyDispose;
import com.wqnmdb.im.netty.handler.BaseHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * 心跳Handler
 */
@Slf4j
@ChannelHandler.Sharable
public class HeartbeatHandler extends ChannelInboundHandlerAdapter implements BaseHandler {

    private final NettyDispose nettyDispose = getNettyDispose();

    private final MsgDispose msgDispose = getMsgDispose();


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyModel.ReqModel reqModel = (NettyModel.ReqModel) msg;

        if (reqModel.getCmd() == ConstantEnum.NETTY_HEARTBEAT.getCode()){
            log.debug("心跳控制器加载客户端报文:{}.", msg);
            msgDispose.pong(ctx);
        }else {
            //执行消息相关指令 传递下一个控制器
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 心跳检测
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        String socketString = ctx.channel().remoteAddress().toString();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.info("Client:{}.READER_IDLE 读超时", socketString);
            } else if (event.state() == IdleState.WRITER_IDLE) {
                log.info("Client:{}.WRITER_IDLE 写超时", socketString);
            } else if (event.state() == IdleState.ALL_IDLE) {
                log.info("Client:{}.ALL_IDLE 超时", socketString);
                //ctx.disconnect();
                nettyDispose.remove(ctx);
            }
        }
    }

}
